import { Picker, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { BaseIngredient, useBaseIngredients } from 'src/hooks/useBaseIngredients';
import { Formula, saveFormulas, useFormulas } from 'src/hooks/useFormulas';
import { useMixIngredient } from 'src/hooks/useMixIngredients';
import { AtButton, AtIcon, AtInput, AtList, AtListItem, AtTextarea } from 'taro-ui';
import { hideLoading, showLoading, showToast } from 'src/utils/toast';

import './index.less';

function FormulaManage() {
  const params = Taro.getCurrentInstance()?.router?.params
  const mixIngredientId = params?.id
  const [currentMixIngredient] = useMixIngredient(mixIngredientId)
  const [formulas = [], setFormulas, fetchFormulas] = useFormulas(params?.id)
  const [baseIngredients] = useBaseIngredients()

  const validateFormulas = (_formulas) => {
    const hasEmpty = _formulas.some((formula) => {
      return !formula.bid || !formula.rate
    })
    if (hasEmpty) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
      })
      return false
    }
    return true
  }

  const handleChange = (type: keyof Formula, index: number) => {
    return (value) => {
      const _formulas = [...formulas]
      _formulas.splice(index, 1, {
        ...formulas[index],
        [type]: value
      })
      setFormulas(_formulas)
    }
  }

  const handleDelete = (index: number) => {
    return () => {
      const _formulas = [...formulas]
      _formulas.splice(index, 1)
      setFormulas(_formulas)
    }
  }

  const handleChangeBaseIngredient = (index: number, _baseIngredients: BaseIngredient[]) => {
    return (e) => {
      const selectedItem = _baseIngredients[e.detail.value]
      handleChange('bid', index)(selectedItem.id)
    }
  }

  const handleSaveFormulas = async () => {
    const normalizeFormulas = formulas.map((formula) => {
      return {
        ...formula,
        rate: Number(formula.rate)
      }
    })
    if (validateFormulas(normalizeFormulas)) {
      showLoading('保存中')
      await saveFormulas(mixIngredientId, normalizeFormulas)
      await fetchFormulas()
      hideLoading()
      showToast('保存成功')
    }
  }

  const handleAdd = () => {
    setFormulas([
      ...formulas,
      {
        bid: '',
        rate: 0
      }
    ])
  }

  const InputArea = (_formula: Formula, index: number) => {
    const selectedItem = baseIngredients.find(item => item.id === _formula.bid)
    // 过滤掉在 formulas 中已经选择的基础调料
    const _baseIngredients = baseIngredients.filter(item => {
      return !formulas.some(formula => formula.bid === item.id)
    })
    let selectedItemIndex = -1
    if (selectedItem) {
      _baseIngredients.unshift(selectedItem)
      selectedItemIndex = 0
    }
    return (
      <View>
        <Picker
          mode='selector'
          range={_baseIngredients}
          rangeKey='name'
          onChange={handleChangeBaseIngredient(index, _baseIngredients)}
          value={selectedItemIndex}
        >
        <AtList hasBorder={false}>
          <AtListItem
            title='基础调料'
            extraText={selectedItem?.name}
            arrow='right'
          />
        </AtList>
        </Picker>
      </View>
    )
  }

  return (
    <View>
      <View className='header'>
        <View className='header-name'>「{currentMixIngredient?.name}」配方</View>
      </View>
      <View className='body'>
        {
          formulas.map((formula, index) => (
            <View key={formula.id} className='formula-manage__item-wrap'>
              <View className='formula-manage__item'>
                {InputArea(formula, index)}
                <AtInput
                  name='rate'
                  title='比例'
                  type='digit'
                  placeholder='请输入比例'
                  border={false}
                  value={formula.rate?.toString?.()}
                  onChange={handleChange('rate', index)}
                />
                <AtTextarea
                  className='formula-manage-remark'
                  value={formula.remark || ''}
                  onChange={handleChange('remark', index)}
                  placeholder='请输入备注（非必填）'
                />
              </View>
              <AtIcon
                value='subtract-circle'
                size='20'
                color='#F00'
                className='formula-manage__item-delete'
                onClick={handleDelete(index)}
              />
            </View>
          ))
        }
        <AtButton
          className='formula-manage__submit'
          type='secondary'
          onClick={handleAdd}
        >
          添加配置
        </AtButton>
        <AtButton
          className='formula-manage__submit'
          type='primary'
          onClick={handleSaveFormulas}
        >
          保存配方
        </AtButton>
      </View>
    </View>
  );
}

export default FormulaManage;
